<template>
  <view class="min-h-screen w-full max-w-[750rpx] bg-[#e0e0e0] mx-auto pb-[120rpx]">
    <backView :back="goBack"/>

    <!-- 页面标题 -->
    <view class="bg-[#27c530] text-white p-[30rpx] rounded-b-[20rpx]">
      <text class="text-[32rpx] font-bold text-center block">{{ "个案记录" }}</text>
    </view>

    <view class="p-[24rpx] pb-[120rpx]">
      <view class="space-y-[24rpx]">
        <view class="bg-white rounded-[20rpx] shadow-md overflow-hidden">
          <view class="bg-[#f4f9f4] p-[24rpx] border-b border-gray-100">
            <text class="text-[30rpx] font-bold text-gray-800">健康档案模块</text>
            <text class="block text-[22rpx] text-gray-500 mt-[8rpx]">
              请选择需要填写或查看的模块，点击进入后可编辑对应内容
            </text>
          </view>
          <view>
            <view
              v-for="item in sectionMenu"
              :key="item.key"
              class="flex items-center justify-between px-[24rpx] py-[28rpx] border-b border-gray-100 active:opacity-80"
              @click="openSection(item)"
            >
              <view class="flex-1 pr-[16rpx]">
                <text class="text-[28rpx] font-medium text-gray-800">{{ item.title }}</text>
                <text class="block text-[22rpx] text-gray-500 mt-[8rpx] leading-tight">
                  {{ item.description }}
                </text>
              </view>
              <text class="text-[32rpx] text-gray-400">›</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="flex-center gap-[16rpx] mt-[32rpx] w-full">
        <nut-button type="default" size="normal" class="flex-1" @click="goBack">取消</nut-button>
        <nut-button type="success" size="normal" class="flex-1" @click="submitForm">保存</nut-button>
        <nut-button type="primary" size="normal" class="flex-[1.64] btnss" v-if="pinggu" @click="changeHealthAssessmentStatus">转为入户工单</nut-button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import Taro from "@tarojs/taro";
import { request } from "@/service/request";
import { localStg } from "@/utils";
import { PageItem } from "./fields";
import backView from "@/components/backView.vue";
import { useMedicalRecordStore } from "@/store/modules";

// 获取 store 实例
const medicalRecordStore = useMedicalRecordStore();

interface SectionMenuItem {
  key: string;
  title: string;
  description: string;
  path: string;
}

const sectionMenu: SectionMenuItem[] = [
  { key: "basicInfo", title: "基本信息", description: "查看服务对象的基础档案与就诊时间", path: "pages/newcs/basic-info" },
  { key: "medicalInstitution", title: "就诊机构", description: "填写或查看就诊医院、科室等信息", path: "pages/newcs/medical-institution" },
  { key: "chiefComplaint", title: "主诉", description: "记录当前主诉症状与体征", path: "pages/newcs/chief-complaint" },
  { key: "presentIllness", title: "现病史", description: "填写现病史相关信息与用药记录", path: "pages/newcs/present-illness" },
  { key: "pastHistory", title: "既往史", description: "记录手术史、外伤史、输血史等信息", path: "pages/newcs/past-history" },
  { key: "personalHistory", title: "个人史", description: "填写个人生活习惯及相关史", path: "pages/newcs/personal-history" },
  { key: "familyHistory", title: "家族史", description: "记录家庭成员健康史与遗传性疾病情况", path: "pages/newcs/family-history" },
  { key: "admission", title: "是否收案", description: "确认是否纳入照护服务范围", path: "pages/newcs/admission" },
  { key: "healthEvaluation", title: "健康评估", description: "进入全面评估、专科评估、居家护理和健康属性优化", path: "pages/newcs/health-evaluation" },
  { key: "diagnosisInfo", title: "诊断信息", description: "填写诊断结果、依据与职业等信息", path: "pages/newcs/diagnosis-info" },
  { key: "treatmentPlan", title: "治疗计划与方案", description: "管理用药计划及预防接种等方案", path: "pages/newcs/treatment-plan" },
  { key: "measures", title: "服务措施", description: "记录具体服务措施与执行情况", path: "pages/newcs/measures" },
  { key: "evaluation", title: "评估总结", description: "填写随访评估与健康建议", path: "pages/newcs/evaluation" },
  { key: "feedback", title: "反馈记录", description: "记录客户及家属反馈", path: "pages/newcs/feedback" },
];

const openSection = (item: SectionMenuItem) => {
  const url = `/${item.path}`;
  Taro.navigateTo({ url });
};

// 记录ID，用于判断是新增还是编辑
const recordId = ref("");

const now = ref(false);
const pinggu = ref(false);

onMounted(async () => {
  const urlParams = new URLSearchParams(window.location.search);
  pinggu.value = urlParams.get("pinggu") == "1";

  // 获取路由参数
  const params = Taro.getCurrentInstance().router?.params;
  console.log("路由参数:", params);

  now.value = !!params?.now;

  if (params?.id) {
    // 如果有ID参数，说明是查看/编辑模式
    recordId.value = params.id;
    console.log("编辑模式，记录ID:", recordId.value);

    // 加载现有数据
    await loadRecordData(params.id);
    return;
  }

  if (now.value) {
    await getCurRecord();
    return;
  }

  // 新增模式
  console.log("新增模式");
  initCurRecord();
});

function initCurRecord() {
  // 初始化 store 数据
  medicalRecordStore.initializeFormData();

  // 从本地存储获取用户基本信息
  const obj = localStg.get("demographicInfo");
  console.log("用户信息:", obj);

  if (obj) {
    // 更新 store 中的基本信息
    medicalRecordStore.updateField("name", obj.name || "");
    medicalRecordStore.updateField("idNumber", obj.idNumber || "");
    medicalRecordStore.updateField("recordid", obj.recordid || "");
  }

  // 设置默认就诊时间为当前时间
  const date = new Date();
  medicalRecordStore.updateField("visitTime", date.toISOString());
}

async function getCurRecord() {
  const obj = localStg.get("demographicInfo");
  const { success } = await request.get<any>(
    `${PageItem.commUrl}/list`,
    {
      idNumber: obj.idNumber,
      column: "createTime",
      order: "desc",
    },
    {
      useErrMsg: true,
    }
  );
  console.log("success cur record", success);
  if (success.records.length > 0) {
    initRecordData(success.records[0]);
  } else {
    initCurRecord();
  }
}

function initRecordData(success: any) {
  if (success) {
    console.log("加载的记录数据:", success);

    // 如果有 note 数据，尝试解析并加载到 store
    if (success.note) {
      try {
        const noteData = JSON.parse(success.note);
        console.log("解析的 note 数据:", JSON.parse(success.note));

        // 转换为扁平化的表单数据
        const formData = medicalRecordStore.noteToFormData(noteData);

        // 设置基本信息
        formData.id = success.id || "";
        formData.name = success.name || "";
        formData.idNumber = success.idNumber || "";
        formData.recordid = success.recordid || "";

        // 初始化表单数据
        medicalRecordStore.initializeFormData(formData);
      } catch (parseError) {
        console.error("解析 note 数据失败:", parseError);
        // 如果解析失败，使用默认数据并填充基本信息
        medicalRecordStore.initializeFormData();
      }
    } else {
      // 如果没有 note 数据，使用默认数据
      medicalRecordStore.initializeFormData();
    }

    // 更新基本信息到 store
    medicalRecordStore.updateField("id", success.id || "");
    medicalRecordStore.updateField("name", success.name || "");
    medicalRecordStore.updateField("idNumber", success.idNumber || "");
    medicalRecordStore.updateField("recordid", success.recordid || "");

    // 更新其他字段到 store（如果 note 中没有的话）
    if (success.seeDate) {
      medicalRecordStore.updateField("visitTime", success.seeDate);
    }
    if (success.diagnosisResult) {
      medicalRecordStore.updateField("diagnosisResult", success.diagnosisResult);
    }
    if (success.diagnosisBasis) {
      medicalRecordStore.updateField("diagnosisBasis", success.diagnosisBasis);
    }
    if (success.hospital) {
      medicalRecordStore.updateField("hospital", success.hospital);
    }
    if (success.department) {
      medicalRecordStore.updateField("department", success.department);
    }
    if (success.dept) {
      medicalRecordStore.updateField("dept", success.dept);
    }
    if (success.project) {
      medicalRecordStore.updateField("project", success.project);
    }
    if (success.specialistAssessment) {
      medicalRecordStore.updateField("specialistAssessment", success.specialistAssessment);
    }
    if (success.surgeryName) {
      medicalRecordStore.updateField("surgeryName", success.surgeryName);
    }
    if (success.surgeryTime) {
      medicalRecordStore.updateField("surgeryTime", success.surgeryTime);
    }
    if (success.surgeryHospital) {
      medicalRecordStore.updateField("surgeryHospital", success.surgeryHospital);
    }
    if (success.medicationAllergy) {
      medicalRecordStore.updateField("medicationAllergy", success.medicationAllergy);
    }
    if (success.foodAllergy) {
      medicalRecordStore.updateField("foodAllergy", success.foodAllergy);
    }
    if (success.otherAllergy) {
      medicalRecordStore.updateField("otherAllergy", success.otherAllergy);
    }
    if (success.familyDiseaseHistory) {
      medicalRecordStore.updateField("familyHistory", success.familyDiseaseHistory);
    }
    if (success.physicalExamination) {
      medicalRecordStore.updateField("physicalExamination", success.physicalExamination);
    }
    if (success.organExamination) {
      medicalRecordStore.updateField("organExamination", success.organExamination);
    }
    if (success.auxiliaryExamination) {
      medicalRecordStore.updateField("auxiliaryExamination", success.auxiliaryExamination);
    }
    if (success.prescription) {
      medicalRecordStore.updateField("prescription", success.prescription);
    }
    if (success.disposition) {
      medicalRecordStore.updateField("disposition", success.disposition);
    }
    if (success.healthEducation) {
      medicalRecordStore.updateField("healthEducation", success.healthEducation);
    }
  }
}

/**
 * 加载记录数据
 */
async function loadRecordData(id: string) {
  try {
    console.log("开始加载记录数据，ID:", id);

    // 请求记录详情
    const { success } = await request.get<any>(
      `${PageItem.commUrl}/queryById`,
      {
        id: id,
      },
      {
        useErrMsg: true,
      }
    );

    initRecordData(success);
  } catch (error) {
    console.error("加载记录数据失败:", error);
    Taro.showToast({ title: "加载数据失败", icon: "error" });
  }
}

async function submitForm() {
  try {
    console.log("开始提交表单数据");

    // 获取当前表单数据
    const formData = medicalRecordStore.getData;

    // 基本验证
    if (!formData?.name) {
      Taro.showToast({ title: "请输入姓名", icon: "error" });
      return;
    }
    if (!formData?.idNumber) {
      Taro.showToast({ title: "请输入证件号码", icon: "error" });
      return;
    }

    // 使用 store 的保存方法
    const result = await medicalRecordStore.saveToPastMedicalInfo(recordId.value);

    if (result.success) {
      console.log("保存成功:", result);

      // 如果是新增模式，更新 recordId
      if (!recordId.value && result.data?.id) {
        recordId.value = result.data.id;
      }

      Taro.showToast({ title: "保存成功", icon: "success" });

      // 延迟返回上一页
      setTimeout(() => {
        Taro.navigateBack();
      }, 1500);
    } else {
      console.error("保存失败:", result.message);
      Taro.showToast({ title: result.message || "保存失败", icon: "error" });
    }
  } catch (error) {
    console.error("保存失败:", error);
    Taro.showToast({ title: "保存失败", icon: "error" });
  }
}

function goBack() {
  console.log("goBack")
  const params = new URLSearchParams(window.location.search);
  const pinggu = params.get("pinggu");
  if(pinggu){
    Taro.navigateBack();
  }
  else{
    history.back()
  }
}

async function changeHealthAssessmentStatus(orderId: String, isMedicalOrder: number) {
  console.log('转为入户工单，id = ' + orderId);
  // 给小程序的webview发送消息
  if(window.wx){
    wx.miniProgram.postMessage({
      data: {
        type: 'goToOrder'
      }
    });
    wx.miniProgram.navigateBack();
  }
}
</script>

<style scoped lang="scss">
.btnss{
  white-space: nowrap;
}
</style>
